<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\taglib;

use buwang\traits\JsonTrait;
use buwang\traits\JwtTrait;
use think\template\TagLib;
use app\manage\model\Admin;
use app\manage\model\Member;
use app\manage\model\AuthGroupNode;
use app\manage\model\AuthNode;
use app\manage\model\AuthGroup;
use app\manage\model\AuthGroupAccess;

/**
 * 权限标签
 * @category   Think
 * @package  Think
 * @subpackage  Driver.Taglib
 * @author   jyk
 */
class Auth extends Taglib
{

    use JsonTrait;
    use JwtTrait;

    /**
     * 定义标签列表
     */
    protected $tags = [
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        // 'close'     => ['attr' => 'time,format', 'close' => 0], //闭合标签，默认为不闭合
        'node' => ['attr' => 'name', 'close' => 1, 'level' => 4],//节点标签
        'group' => ['attr' => 'name', 'close' => 1, 'level' => 4],//组标签
    ];


    /**
     * 节点标签
     */
    public function tagnode($tag, $content)
    {
        $topAdminId = config('auth.super_admin_id');//超级管理员id
        $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
        $name = $tag['name']; // 权限标识
        $type = 0;
        $jump = false;
        //得到登录信息
        $token = get_token(app("app\Request"));

        if ($token) {
            $jwtinfo = self::decodeToken($token);//解析token,获取用户信息
            $login_type = $jwtinfo->scopes;
            $user = null;
            switch ($login_type) {
                case "admin":
                    $user = Admin::find($jwtinfo->data->id);
                    if ($topAdminId == $user['id']) $jump = true;
                    break;
                case "member":
                    $user = Member::find($jwtinfo->data->id);
                    break;
            }

            if ($user) {
                if (!$jump) {
                    // 查询权限
                    //查询用户组
                    $group_ids = AuthGroupAccess::where('uid', $user['id'])->where('scopes', $login_type)->column('group_id');
                    if (!in_array($topAdminRoleId, $group_ids)) {

                        //过滤无效的角色
                        $group_ids = AuthGroup::where('id', 'in', $group_ids)->where('status', 1)->column('id');
                        $group_ids = implode(",", $group_ids);//数组合并成字符串
                        $admin_group = $group_ids;
                        //TODO 查询该管理员是否拥有该节点权限
                        $res = AuthGroupNode::where('auth_name', '=', $name)->where('group_id', 'in', $admin_group)->find();
                        if ($res) $res = AuthNode::where('status', 1)->find($res['node_id']);
                        // echo AuthGroupNode::getLastSql();die;//打印最后一条sql
                        if ($res) $type = 1;
                    } else {
                        $type = 1;
                    }

                } else {
                    $type = 1;
                }
            }
        }
        $type = 1;
        $num = mt_rand(0, 999);
        $null = '';
        $parse = '<?php ';
        $parse .= '$t_' . $num . ' = ' . $type . ';';
        $parse .= ' ?>';
        $parse .= '{eq name="t_' . $num . '" value="1"}';
        $parse .= $content;
        $parse .= '{else/}';
        $parse .= $null;
        $parse .= '{/eq}';

        if ($name = '/manage/admin.SysPlugin/install') {
            //file_put_contents('tagnode.txt', $parse);//写入文件，一般做正式环境测试
        }
        return $parse;
    }

    /**
     * 组标签
     */
    public function taggroup($tag, $content)
    {
        $name = $tag['name']; // 权限标识
        $type = 0;
        $topAdminId = config('auth.super_admin_id');//超级管理员id
        $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
        //得到登录信息
        $token = get_token(app("app\Request"));
        //$token =  'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3d3cuYnV3YW5neXVuLmNvbSIsImF1ZCI6ImJ1d2FuZyIsImlhdCI6MTU5MTkyOTI3NiwibmJmIjoxNTkxOTI5Mjc2LCJkYXRhIjp7InVpZCI6MSwibmlja25hbWUiOiJBZG1pbiIsIm1vYmlsZSAiOiIifSwic2NvcGVzIjoiYWRtaW4iLCJleHAiOjE1OTI1MzQwNzZ9.-voCyZjI_XPCPSw3VjHWfVfwk9Xtp4GDrx1db5xJQwE';
        $jump = false;
        if ($token) {
            $jwtinfo = self::decodeToken($token);//解析token,获取用户信息
            $login_type = $jwtinfo->scopes;
            $user = null;

            switch ($login_type) {
                case "admin":
                    $user = Admin::find($jwtinfo->data->uid);
                    if ($topAdminId == $user['id']) $jump = true;
                    break;
                case "member":
                    $user = Member::find($jwtinfo->data->uid);
                    break;
            }
            if ($user) {
                if (!$jump) {
                    // 查询权限
                    //是否拥有超级管理员角色
                    $is_super = AuthGroupAccess::where('uid', $user['id'])->where('group_id', $topAdminRoleId)->find();
                    if (!$is_super) {
                        //查询用户组
                        $res = AuthGroupAccess::field('a.id')
                            ->alias('a')
                            ->join('bw_auth_group g', 'a.group_id = g.id', 'left')
                            ->where('a.uid', $user['id'])
                            ->where('a.scopes', $login_type)
                            ->where('g.group_name', $name)
                            ->where('g.status', 1)
                            ->find();

                        if ($res) $type = 1;
                    } else {
                        $type = 1;
                    }

                } else {
                    $type = 1;
                }

            }

        }
        $type = 1;
        $num = mt_rand(0, 999);
        $null = '';
        $parse = '<?php ';
        $parse .= '$t2_' . $num . ' = ' . $type . ';';
        $parse .= ' ?>';
        $parse .= '{eq name="t2_' . $num . '" value="1"}';
        $parse .= $content;
        $parse .= '{else/}';
        $parse .= $null;
        $parse .= '{/eq}';
        return $parse;
    }

}